package com.voodoo.lib_frame.httpTools;

import com.voodoo.lib_frame.Config;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 开发者：  voodoo_jie
 * <br>创建时间： 2018/06/24 024 下午 11:34.
 * <br>功能描述： 创建okHttpclient对象，并且配置支持https，以及发送请求
 */
public class CommonOkhttpClient {

    private static OkHttpClient okHttpClient = null;

    // 为okHttpClient去配置参数并添加请求头 类加载的时候开始创建静态代码块，并且只执行一次
    static {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(Config.TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.writeTimeout(Config.TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.readTimeout(Config.TIME_OUT, TimeUnit.SECONDS);
        okHttpClientBuilder.followRedirects(true); //设置重定向 其实默认也是true

        // 添加请求头，这个看个人需求
        okHttpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request()
                        .newBuilder()
//                        .addHeader("Content-Type", "text/html: charset=UTF-8")
//                        .addHeader("Token", "需要的话可在此处添加Token")
                        .addHeader("User-Agent", "Android") // 标明发送本次请求的客户端
                        .build();
                return chain.proceed(request);
            }
        });

        // 添加https支持
        okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        // 授权https
        okHttpClientBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory(), HttpsUtils.initTrustManager());
        okHttpClient = okHttpClientBuilder.build();
    }

    public static Call sendRequest(Request request) {
        return okHttpClient.newCall(request);
    }

    public static void cancelTag(Object tag) {
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : okHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }
}
